package com.wk.paradise.redis.utils;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import com.wk.paradise.redis.bean.Club;
import java.lang.reflect.ParameterizedType;

/**
 * @Classname ProtostuffSerializerUtil
 * @Description TODO
 * @Date 2019/12/21 17:58
 * @Author by weikai
 */
public final class ProtostuffSerializerUtil<T> {

  private ProtostuffSerializerUtil() {
  }

  /**
   * 序列化
   * @param t 需要序列化的对象
   * @param <T>
   * @return
   */
  public static <T> byte[] serialize(T t) {
    final LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    Schema<Object> schema = RuntimeSchema.createFrom((Class<Object>) t.getClass());
    try {
      return serializeInternal(t, schema, buffer);
    } catch (final Exception e) {
      throw new IllegalStateException(e.getMessage(), e);
    } finally {
      buffer.clear();
    }
  }

  /**
   * 反序列化
   * @param bytes
   * @return
   */
  public static <T> T deserialize(T t,final byte[] bytes) {
//    Class <T> entityClass = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    Schema<T> schema = (Schema<T>) RuntimeSchema.createFrom(t.getClass());
    try {
      T t1 = deserializeInternal(bytes, schema.newMessage(), schema);
      if (t1 != null ) {
        return t1;
      }
    } catch (final Exception e) {
      throw new IllegalStateException(e.getMessage(), e);
    }
    return null;
  }

  private static <T> byte[] serializeInternal(final T source, final Schema<T>
      schema, final LinkedBuffer buffer) {
    return ProtostuffIOUtil.toByteArray(source, schema, buffer);
  }
  private static  <T> T deserializeInternal(final byte[] bytes, final T result, final
  Schema<T> schema) {
    ProtostuffIOUtil.mergeFrom(bytes, result, schema);
    return result;
  }

}
